﻿using K3Cloud.WebApi.Core.IoC.Cache;
using K3Cloud.WebApi.Core.IoC.Extensions;
using K3Cloud.WebApi.Core.IoC.K3Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using K3Ioc = K3Cloud.WebApi.Core.IoC.K3IOCServiceCollectionExtensions;

namespace K3Cloud.WebApi.Core.IoC;
/// <summary>
/// 
/// </summary>
public class K3Services
{
    /// <summary>
    /// 通过K3Config注册K3Cloud
    /// </summary>
    public static void AddK3Sugar(K3Config? config, ICacheService? cache = null)
    {
        ServiceCollection services = new();
        InitializeServices(services, config);
    }
    /// <summary>
    /// 通过K3Config注册K3Cloud
    /// </summary>
    public static void AddK3Sugar(Action<K3Config> setupAction, ICacheService? cache = null)
    {
        if (setupAction == null) throw new ArgumentNullException(nameof(setupAction));
        K3Config k3Config = new();
        setupAction(k3Config);
        AddK3Sugar(k3Config, cache);
    }
    /// <summary>
    /// 读取appsettings.json配置文件注册K3Cloud
    /// </summary>
    public static void AddK3Sugar(ICacheService? cache = null)
    {
        IConfigurationRoot builder = new ConfigurationBuilder()
             .AddInMemoryCollection()
             .AddJsonFile("appsettings.json", optional: false)
             .Build();

        IConfigurationSection k3CloudConfig = builder.GetSection("K3CLOUDCONFIG");
        if (k3CloudConfig == null) throw new ArgumentNullException(nameof(k3CloudConfig));
        K3Config? k3Config = builder.GetValue<K3Config>("K3CLOUDCONFIG") ?? builder.GetSection("K3CLOUDCONFIG").GetChildren().FirstOrDefault()?.Get<K3Config>();
        AddK3Sugar(k3Config, cache);
    }
    private static void InitializeServices(IServiceCollection services, K3Config? config)
    {
        K3Ioc.Configs = config ?? throw new ArgumentNullException(nameof(config));
        ConfigureK3Config(services, config);
        services.AddDefaultHttpClient(K3Ioc._cookie);
        var scope = services.BuildServiceProvider();
        K3Ioc.CacheService = scope.GetService<ICacheService>() ?? AddDefaultCacheService(services);
        K3Ioc.HttpClient = scope.GetRequiredService<K3HttpService>();
    }

    private static ICacheService AddDefaultCacheService(IServiceCollection services)
    {
        services.AddSingleton<ICacheService, MemoryCacheService>();
        using var innerScope = services.BuildServiceProvider().CreateScope();
        return innerScope.ServiceProvider.GetRequiredService<ICacheService>();
    }
    private static void ConfigureK3Config(IServiceCollection services, K3Config config)
    {
        services.Configure<K3Config>(cfg =>
        {
            cfg.AcctId = config.AcctId;
            cfg.AppID = config.AppID;
            cfg.AppSecret = config.AppSecret;
            cfg.UserName = config.UserName;
            cfg.Password = config.Password;
            cfg.LCID = config.LCID;
            cfg.ServerHost = config.ServerHost;
            cfg.ConnectionValidTime = config.ConnectionValidTime;
        });
    }
}
